import logging
from logging.handlers import RotatingFileHandler
import redis
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect, generate_csrf
from flask_session import Session
from config import config
from info.commons import index_class

redis_store = None
db = SQLAlchemy()


def setup_log(config_name):
    """配置日志"""

    # 1. 配置日志的记录等级
    logging.basicConfig(level=config[config_name].LOG_LEVEL)
    # 2. 创建日志记录器，配置日志的存储路径，每个日志文件的最大大小，保存日志的个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024*1024*100, backupCount=10)
    # 3. 创建日志记录的格式，日志等级 输入日志信息的文件名 行数
    formatter = logging.Formatter("%(levelname)s %(filename)s:%(lineno)d %(message)s")
    # 4. 为日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 5.为全局日志工具对象添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


def create_app(config_name):
    setup_log(config_name)

    app = Flask(__name__)
    app.config.from_object(config[config_name])

    # 配置redis
    global redis_store
    redis_store = redis.StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT, decode_responses=True)

    db.init_app(app)

    CSRFProtect(app)

    Session(app)

    from info.modules.index import index_blue
    app.register_blueprint(index_blue)

    # 注册登陆蓝图到app中
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)

    from info.modules.news import news_blue
    app.register_blueprint(news_blue)

    # 使用请求钩子拦截所有的请求
    @app.after_request
    def set_csrf_token(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    app.add_template_filter(index_class, 'index_class')
    return app

